package com.qf.flash.app;


import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.utils.ChatUserCacheMgr;
import com.qf.dblib.dao.entity.UserInfo;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.constant.Constants;
import com.qf.flash.ui.chat.db.ChatHelper;
import com.qf.flashlib.app.BaseApp;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.litepal.LitePal;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 2018/11/12 14:38
 */
public class MyApp extends BaseApp {
    //全局上下文
    private static Context mContext;
    // 日志开关
    public static boolean logcat = true;
    public static IWXAPI mWxApi;

    @Override
    protected void initSDK() {
        //        new ANRWatchDog().start();
        if (!isMainProcess()) {
            return;
        }
        initRefresh();
        initDao();
        mContext = getApplicationContext();
        //环信初始化
        initChat();
        //  微信
        initWx();
        // 极光推送初始化
        initJpush();
    }

    private void initJpush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        UserInfo loginUser = UserMgr.getInstance().getLoginUser();
        if (loginUser != null)
            JPushInterface.setAlias(this, 9,loginUser.getUid());
    }

    private void initWx() {
        mWxApi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, true);
        mWxApi.registerApp(Constants.WX_APP_ID);
    }

    private void initChat() {

        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        // 是否自动将消息附件上传到环信服务器，默认为True是使用环信服务器上传下载，如果设为 false，需要开发者自己处理附件消息的上传和下载
        options.setAutoTransferMessageAttachments(true);
        // 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);

        //初始化
        EaseUI.getInstance().init(this, options);
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(true);
        EaseUI.getInstance().setUserProfileProvider(ChatUserCacheMgr.getInstance());

        ChatHelper.getInstance().init(mContext);

    }

    private boolean isMainProcess() {
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        // 如果APP启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

        return processAppName != null && processAppName.equalsIgnoreCase(this.getPackageName());

    }


    /**
     * 初始化数据库
     */
    private void initDao() {
        LitePal.initialize(this);
    }


    private void initRefresh() {
        //设置刷新文字
        ClassicsHeader.REFRESH_HEADER_PULLING = getString(R.string.refresh_header_pulling);
        ClassicsHeader.REFRESH_HEADER_REFRESHING = getString(R.string.refresh_header_refreshing);
        ClassicsHeader.REFRESH_HEADER_LOADING = getString(R.string.refresh_header_loading);
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(R.string.refresh_header_release);
        ClassicsHeader.REFRESH_HEADER_FINISH = getString(R.string.refresh_header_finish);
        ClassicsHeader.REFRESH_HEADER_FAILED = getString(R.string.refresh_header_failed);
        //设置加载文字
        ClassicsFooter.REFRESH_FOOTER_PULLING = getString(R.string.refresh_footer_pulling);
        ClassicsFooter.REFRESH_FOOTER_RELEASE = getString(R.string.refresh_footer_release);
        ClassicsFooter.REFRESH_FOOTER_LOADING = getString(R.string.refresh_footer_loading);
        ClassicsFooter.REFRESH_FOOTER_REFRESHING = getString(R.string.refresh_footer_refreshing);
        ClassicsFooter.REFRESH_FOOTER_FINISH = getString(R.string.refresh_footer_finish);
        ClassicsFooter.REFRESH_FOOTER_FAILED = getString(R.string.refresh_footer_failed);
        ClassicsFooter.REFRESH_FOOTER_NOTHING = getString(R.string.refresh_footer_nothing);
    }


    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.white, R.color.color_666666);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }


    public static Context getAppContext() {
        return mContext;
    }


}
